package vip.zcn.mrn.service.impl;


import org.springframework.stereotype.Service;
import vip.zcn.mrn.model.Dept;
import vip.zcn.mrn.service.DeptService;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class DeptServiceImpl implements DeptService {
    // 模拟存储
    private static final Map<String, Dept> deptMap = new HashMap<>();
    static {
        Dept root = new Dept(); root.setId("1"); root.setName("总部"); root.setParentId(null);
        Dept child1 = new Dept(); child1.setId("2"); child1.setName("分部A"); child1.setParentId("1");
        Dept child2 = new Dept(); child2.setId("3"); child2.setName("分部B"); child2.setParentId("1");
        Dept subChild = new Dept(); subChild.setId("4"); subChild.setName("子部门B1"); subChild.setParentId("3");
        deptMap.put("1", root);
        deptMap.put("2", child1);
        deptMap.put("3", child2);
        deptMap.put("4", subChild);
    }

    @Override
    public String deleteDept(String deptId) {
        if (!deptMap.containsKey(deptId)) {
            return "部门不存在";
        }
        deleteRecursively(deptId);
        return "删除成功";
    }

    private void deleteRecursively(String deptId) {
        // 收集所有需要删除的子部门ID
        List<String> toDelete = new ArrayList<>();
        for (Dept d : deptMap.values()) {
            // 如果当前部门的父ID等于要删除的部门ID，则将其加入待删除列表
            if (deptId.equals(d.getParentId())) {
                toDelete.add(d.getId());
            }
        }
        // 递归删除所有子部门
        for (String childId : toDelete) {
            deleteRecursively(childId);
        }
        // 从map中移除当前部门
        deptMap.remove(deptId);
    }
}